//
//  AddBusinessActivityVC.m
//  WoWeiRenRenOC
//
//  Created by 姜伟 on 2020/3/18.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "AddBusinessActivityVC.h"

@interface AddBusinessActivityVC () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIGestureRecognizerDelegate>
{
    UIImagePickerController *_imagePicker; // 图片选择控制器
    BOOL _IsCamera; // 是否调用相机
    UIImage *_image;
}

@property (weak, nonatomic) IBOutlet IQTextView *introduceText;
@property (weak, nonatomic) IBOutlet UIImageView *activityImage;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
@property (weak, nonatomic) IBOutlet UIImageView *addImage;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIView *saveBg;

@property (copy, nonatomic) __block NSString *imagePath;

@end

@implementation AddBusinessActivityVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.saveBg.layer.cornerRadius = 4;
    [self.addImage addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(create_ActionSheet)]];
    
    if (self.model) {
        self.title = @"编辑特价活动";
        self.deleteBtn.hidden = NO;
        SD_SETIMAGE_PlaceHolder(self.addImage, self.model.img_path, @"default_image_square")
        self.introduceText.text = self.model.activity_name;
        self.imagePath = self.model.img_path;
        
        UIBarButtonItem *deleteBtn = [[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonClick)];
        self.navigationItem.rightBarButtonItem = deleteBtn;
    }
    else {
        self.title = @"新增特价活动";
        self.deleteBtn.hidden = YES;
    }
}

- (void)rightBarButtonClick
{
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"提示" message:@"是否删除该活动" preferredStyle:UIAlertControllerStyleAlert];
    WeakSelf(ws)
    [alertController addAction: [UIAlertAction actionWithTitle: @"确定" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [ws deleteActivity];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    [self presentViewController: alertController animated:YES completion:nil];
}

- (void)deleteActivity
{
    SVPShowInternetWaiting
    [NetRequestTool postUrl:@"business/deleteActivityById" parameters:@{@"business_activity_id":@(self.model.business_activity_id)} success:^(id responseObject) {
        SVP(@"删除成功");
        [self.parentsVC needRefresh];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        SVPDismiss
    }];
}

- (IBAction)deleteImageClick {
    self.imagePath = nil;
    self.deleteBtn.hidden = YES;
    self.addImage.image = [UIImage imageNamed:@"tianjia"];
}

- (IBAction)saveActivivityClick {
    
    NSString *contentStr = self.introduceText.text;
    if ([CommonTTool isBlankString:contentStr]) {
        SVP(@"请输入活动介绍");
        return;
    }
    if ([CommonTTool isBlankString:self.imagePath]) {
        SVP(@"请添加活动图片");
        return;
    }
    
    SVPShowInternetWaiting
    NSString *hitStr = @"添加成功";
    NSDictionary *para = @{@"activity_name":contentStr, @"img_path":self.imagePath};
    NSString *urlStr = @"business/saveActivity";
    if (self.model) {
        hitStr = @"修改成功";
        para = @{@"business_activity_id":@(self.model.business_activity_id), @"activity_name":contentStr, @"img_path":self.imagePath};
        urlStr = @"business/updateBusinessActivity";
    }
    [NetRequestTool postUrl:urlStr parameters:para success:^(id responseObject) {
        SVP(hitStr)
        [self.parentsVC needRefresh];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        SVPDismiss
    }];
}

#pragma mark - 点击图片事件
- (void)create_ActionSheet {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"选择" message: nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction: [UIAlertAction actionWithTitle: @"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self use_camera];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle:@"我的相册" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        [self pickPhoto];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    [[CommonTTool getCurrentVC] presentViewController: alertController animated: YES completion: nil];
}

#pragma mark - 调用相机
- (void)use_camera {
    _IsCamera = YES;
    UIImagePickerController *imageController = [[UIImagePickerController alloc]init];
    imageController.delegate = self;
    imageController.allowsEditing = NO;
    imageController.sourceType = UIImagePickerControllerSourceTypeCamera;
    [[CommonTTool getCurrentVC] presentViewController:imageController animated:YES completion:nil];
}

#pragma mark - 点击从本地相册调用图片
- (void)pickPhoto {
    _IsCamera = NO;
    UIImagePickerController *imagePickerTemp = [[UIImagePickerController alloc]init];
    _imagePicker = imagePickerTemp;
    _imagePicker.delegate = self;
    _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    _imagePicker.allowsEditing = YES;
    [[CommonTTool getCurrentVC] presentViewController:_imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *headerImg;
    if (_IsCamera) {
        headerImg = [info objectForKey:UIImagePickerControllerOriginalImage];
        if(headerImg.imageOrientation!=UIImageOrientationUp){
            // Adjust picture Angle
            UIGraphicsBeginImageContext(CGSizeMake(headerImg.size.width * 0.4, headerImg.size.height * 0.4));
            [headerImg drawInRect:CGRectMake(0, 0,headerImg.size.width * 0.4, headerImg.size.height * 0.4)];
            headerImg = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        headerImg = [CommonTTool imageCompression:headerImg];
    }
    else {
        headerImg = [info objectForKey:UIImagePickerControllerEditedImage];
    }
    // 图片上传接口
    [self uploadHeadImage:headerImg];
}

- (void)uploadHeadImage:(UIImage *)image {
    __weak typeof(self) weakSelf = self;
    NSArray *imageArray = [NSArray arrayWithObjects:image, nil];
    [NetManager isUpdateImgArr:imageArray andData:nil andFileName:nil success:^(NSDictionary *dic) {
        NSString *imagePath = dic[@"object"];
        SD_SETIMAGE_PlaceHolder(weakSelf.addImage, imagePath, @"default_image_square")
        if (weakSelf.model) {
            weakSelf.model.img_path = imagePath;
        }
        weakSelf.imagePath = imagePath;
        weakSelf.deleteBtn.hidden = NO;
    } uploadProgress:^(NSProgress *_Nonnull str) {
        
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
